package nature.nano.control.script.run;

import java.io.File;
import java.io.IOException;

import nature.nano.component.Strings;
import nature.nano.control.script.assembly.ScriptAssembly;
import nature.nano.control.script.parse.ScriptFileReader;
import nature.nano.control.script.parse.ScriptInputter;
import nature.nano.control.script.parse.ScriptLineParser;
import nature.nano.control.script.parse.StringHelper;
import nature.nano.environment.Config;
import nature.nano.iface.Provider;

public class MetaRunner {

	private static void primary(Provider script) {
		ScriptLineParser parser = new ScriptLineParser();
		ScriptAssembly assembly = new ScriptAssembly();		
		script.plug(Strings.output, parser);
		parser.plug(Strings.output, assembly);
		script.start();
		assembly.start();
	}
	
	public static void run(String script) {
		ScriptInputter inputter = new ScriptInputter();
		inputter.setProp(Strings.script, script);
		primary(inputter);
	}

	public static void run(String... scripts) {
		run(StringHelper.mergeScripts(scripts));
	}
	
	public static void runFile(String file) {
		ScriptFileReader reader = new ScriptFileReader();
		reader.setProp(Strings.file, file);
		primary(reader);
	}
	
	public static void main(String[] args) throws IOException {
		if (args.length != 1) {
			return;
		}
		String fileName = args[0];
		File file = new File(fileName);
		if (!file.exists()) {
			String path = Config.current().getProp(Strings.defaultScriptFolder) + "/" + fileName;
			file = new File(Config.current().getPath(path));
		}
		if (file.exists()) {
			ScriptRunner.runFile(file.getAbsolutePath());			
		} else {
			System.out.println("can't load script file: " + fileName);
		}
	}

}
